package cn.ddiancan.xddcloud.common.security;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

public class SecurityKeyGenerator {

    public static void generaterJwtKey() throws NoSuchAlgorithmException {
        // 初始化KeyPairGenerator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048, new SecureRandom());

        // 生成一个密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        // 打印公钥和私钥
        System.out.println("公钥：" + publicKeyString);
        System.out.println("私钥：" + privateKeyString);
    }

    public static void generaterAesKey(String componentPath) throws Exception {
        for (int i = 1; i <= 2; i++) {
            File file = new File(componentPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File keyFile = new File(componentPath + i + ".key");
            if (!keyFile.exists()) {
                byte[] randomBytes2 = new byte[16];  // 128 bits
                SecureRandom.getInstanceStrong().nextBytes(randomBytes2);
                String key = bytesToHex(randomBytes2);
                file.createNewFile();
                OutputStream fileOutputStream = new FileOutputStream(keyFile);
                fileOutputStream.write(key.getBytes());
                fileOutputStream.close();
            }
        }
    }

    // 将字节数组转换为16进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}